// home模块专用小仓库

import { reqGetCode, reqRegister, reqUserInfo, reqUserLogin, reqUserLogout } from "前台项目/api";

//任何的小仓库:state、mutations、actions、getters 
let state = {
    // 验证码
    code: '',
    //身份标识符很重要【存储在vuex】
    token: localStorage.getItem('TOKEN'),
    // 用户名
    nickName: '',
};
let mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_USERINFO(state, nickName) {
        state.nickName = nickName;
    },
    CLEAR(state){
        // 清除仓库相关的用户信息
        state.token='',
        state.nickName = '',
        // 本地存储令牌清空
        localStorage.removeItem('TOKEN')
    },
};
let actions = {
    // 获取验证码
    async getCode({ state, dispatch, commit }, phone) {
        let result = await reqGetCode(phone);

        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject();
        }

    },

    // 注册用户的地方
    async registerUser({ state, dispatch, commit }, obj) {
        let result = await reqRegister(obj)
        // console.log(result)

        if (result.code == 200) {
            // 成功
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }

    },

    // 用户登录的地方
    async userLogin({ state, dispatch, commit }, data) {
        //接口说明:后台老师目前登录接口返回数据不正确的，以后工作的时候登录接口成功，返回格式100%和相面例子一样的!!!

        let result = await reqUserLogin(data)
        //   console.log(result)
        // 登录成功
        if (result.code == 200) {
            commit('SET_TOKEN', result.data.token)

            // 以后开发的时候  经常的登录成功获取token【持久化存储】
            localStorage.setItem('TOKEN',result.data.token)
            // 成功
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },

    // 获取用户信息
    async getUserInfo({ state, dispatch, commit }) {
        let result = await reqUserInfo()

        if (result.code == 200) {
            commit('SET_USERINFO', result.data.nickName)
            // console.log( result.data.nickName)

            return 'ok'
        } else {
            return Promise.reject()
        }
    },

    // 退出登录的业务
    async logout({ state, dispatch, commit }){
        // 发送请求通知浏览器销毁当前token
        let result = await reqUserLogout()

        if (result.code == 200) {
            commit('CLEAR')

            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }

    }


};
let getters = {};


// 对外暴露一个对象
export default {
    state,
    mutations,
    actions,
    getters
}